package com.kpi.processflow.process;

import com.google.common.collect.Maps;
import com.kpi.processflow.node.Node;
import com.kpi.processflow.process.factory.ProcessFactory;
import com.kpi.processflow.process.registry.ProcessDefinitionRegistry;
import com.sun.istack.internal.NotNull;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Map;

/**
 * @author Kevin Liu
 * @date 2020/5/3 6:35 下午
 */
@Slf4j
@Component
public class DefaultProcessFactory implements ProcessFactory, ProcessDefinitionRegistry {

    private final Map<String,List<Node>> processes = Maps.newHashMap();


    private String buildKey( String bizCode, String operation) {
        return bizCode +
                "#" +
                "operation";
    }

    @Override
    public List<Node> getProcessNodes(@NotNull String bizCode,@NotNull String operation) {
        String key = buildKey(bizCode, operation);
        return processes.get(key);
    }

    @Override
    public List<Node> getProcessNodes(Process process) {
        return getProcessNodes(process.getBizCode(),process.getOperation());
    }

    @Override
    public void registryProcess(@NotNull String bizCode, @NotNull String operation,@NotNull List<Node> nodeList) {
        String key = buildKey(bizCode, operation);
        List<Node> nodes = processes.get(key);
        if(nodes!=null) {
            log.error("bizCode : {}, operation: {} expected single matching process definition but found 2, check your process definition file", bizCode, operation);
            throw new RuntimeException("process definition conflict");
        }
        processes.put(key,nodeList);
    }

    @Override
    public void registryProcess(Process process, List<Node> nodes) {
        registryProcess(process.getBizCode(),process.getOperation(),nodes);
    }
}
